package com.winway.sixbook.ui;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.winway.sixbook.HomeActivity;
import com.winway.sixbook.R;
import com.winway.sixbook.bean.RecordData;
import com.winway.sixbook.custom.CloseActivityClass;
import com.winway.sixbook.service.RecordDataManager;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class NewRecordAdd extends Activity {
	
	private static final String TAG = "NewRecordAdd";
	private RecordDataManager recordDataManager ;
	private TextView recordform_title1;
	private Button savebtn;
	private Button saveAlertbtn;
	private TextView recordform_zm;
	private TextView recordform_fm;
	private TextView recordform_wy;
	private String typename ="财富";
	private String typeid ="1";
	private String recorddataid ="0";
	
	private ImageButton top_tbn_fanhui;
	private Button top_tbn_xinzeng;
	private TextView title;
	
	private TextView recordform_title2;
	private TextView recordform_title3;
	private TextView recordform_title4;
	private String  isqy = "0";
	private String addtime;
	private Button recordform_btn_del,recordform_btn_yz;
	AlertDialog builder = null;
	private boolean flagnew = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_record_add);
		CloseActivityClass.activityList.add(this);
		
		if (recordDataManager == null) {
        	recordDataManager = new RecordDataManager(this);
        	recordDataManager.openDataBase();
        }
		activityInit();
	}
	
	private void activityInit() {
		recordform_title1 = (TextView)findViewById(R.id.recordform_title1);
		savebtn = (Button)findViewById(R.id.recordform_btn_save);
		saveAlertbtn = (Button)findViewById(R.id.recordform_btn_save_Alert);
		recordform_zm = (TextView)findViewById(R.id.recordform_zm);
		recordform_fm = (TextView)findViewById(R.id.recordform_fm);
		recordform_wy = (TextView)findViewById(R.id.recordform_wy);
		
		top_tbn_fanhui = (ImageButton)findViewById(R.id.nagivate_btn_left);
        top_tbn_xinzeng = (Button)findViewById(R.id.navigate_btn_right);
        recordform_btn_yz = (Button)findViewById(R.id.recordform_btn_yz); 
        title = (TextView)findViewById(R.id.title);
        
        recordform_title2 = (TextView)findViewById(R.id.recordform_title2);
        recordform_title3 = (TextView)findViewById(R.id.recordform_title3);
        recordform_title4 = (TextView)findViewById(R.id.recordform_title4);
        
        recordform_btn_del = (Button)findViewById(R.id.recordform_btn_del);
        
        top_tbn_fanhui.setOnClickListener(mListener);
        top_tbn_xinzeng.setVisibility(View.INVISIBLE);
        title.setText("我要添加");
		
		Bundle bundle = new Bundle();
        bundle = this.getIntent().getExtras();
        typename = bundle.getString("typename");
        typeid = bundle.getString("typeid");
        recorddataid = bundle.getString("recorddataid");
        recordform_title1.setText("您选择的是"+typename+"种子");
        savebtn.setOnClickListener(mListener);
        recordform_btn_yz.setOnClickListener(mListener);
        
        if(null != typeid && !"".equals(typeid)){
			if(Integer.parseInt(typeid)==0){
				recordform_title2.setText("今日最好");
				recordform_title3.setText("最需改善");
				recordform_title4.setText("祈愿");
			}else{
				recordform_title2.setText("正面");
				recordform_title3.setText("反面");
				recordform_title4.setText("我要");
			}
		}
        
        if(null != recorddataid){
        	Cursor cursor = recordDataManager.fetchRecordData(Integer.parseInt(recorddataid));
        	recordform_zm.setText(cursor.getString(cursor.getColumnIndex("content_zm")));
			recordform_fm.setText(cursor.getString(cursor.getColumnIndex("content_fm")));
			recordform_wy.setText(cursor.getString(cursor.getColumnIndex("content_wy")));
			addtime = cursor.getString(cursor.getColumnIndex("add_time"));
			recordform_btn_del.setVisibility(View.VISIBLE);
			if(null != typeid && !"".equals(typeid)){
				if(Integer.parseInt(typeid)==0){
					recordform_btn_yz.setVisibility(View.GONE);
				}else{
					recordform_btn_yz.setVisibility(View.VISIBLE);
				}
			}
        }
        recordform_btn_del.setOnClickListener(mListener);
	}
	
	OnClickListener mListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()){
			case R.id.recordform_btn_save:
				String zmstr = recordform_zm.getText().toString().trim();
				String fmstr = recordform_fm.getText().toString().trim();
				String wystr = recordform_wy.getText().toString().trim();
				
				if(null != recorddataid && Integer.parseInt(recorddataid)>0){
					updateRecord(recorddataid,zmstr,fmstr,wystr,addtime,"0");
				}else{
					saveRecord(zmstr,fmstr,wystr,isqy,"0");
				}
				break;
				
			case R.id.recordform_btn_save_Alert:
				//saveRecord();
				Intent counter1 = new Intent(NewRecordAdd.this, AlertActivity.class);
				startActivity(counter1);
				finish();
				break;
			case R.id.nagivate_btn_left:
				Intent counter = new Intent(NewRecordAdd.this, HomeActivity.class);
				startActivity(counter);
				finish();
				break;
			case R.id.recordform_btn_del:
				seeddel(recorddataid,addtime);
				break;
			case R.id.recordform_btn_yz:
				String zmstr1 = recordform_zm.getText().toString().trim();
				String fmstr1 = recordform_fm.getText().toString().trim();
				String wystr1 = recordform_wy.getText().toString().trim();
				if(null != recorddataid && Integer.parseInt(recorddataid)>0){
					updateRecord(recorddataid,zmstr1,fmstr1,wystr1,addtime,"1");
				}
				break;
			}
		}
	};
	
	private void saveRecord(String zmstr, String fmstr, String wystr, String isqy, String isdo) {
		if(dataValid()){
			recordDataManager.openDataBase();
			SimpleDateFormat dateformat1=new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat dateformat2=new SimpleDateFormat("HH");
			SimpleDateFormat dateformat3=new SimpleDateFormat("mm");
			SimpleDateFormat dateformat4=new SimpleDateFormat("ss");
			
	        String addtime = dateformat1.format(new Date());
	        String addhour = dateformat2.format(new Date());
	        String addmin = dateformat3.format(new Date());
	        String addsec = dateformat4.format(new Date());
	        
			RecordData recordData = new RecordData(zmstr, fmstr, wystr, Integer.parseInt(typeid), typename, addtime, Integer.parseInt(addhour),Integer.parseInt(addmin),Integer.parseInt(isqy),Integer.parseInt(addsec),Integer.parseInt(isdo));
			long flag = recordDataManager.insertRecordData(recordData);
			if (flag == -1) {
				Toast.makeText(this, getString(R.string.save_fail),Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(this, getString(R.string.save_sucess),Toast.LENGTH_SHORT).show();
				Intent addintent = new Intent(NewRecordAdd.this, NextWyAlarmActivity.class);
				Bundle bundle = new Bundle(); 
				bundle.putString("Addtime", dateformat1.format(new Date()));
				addintent.putExtras(bundle); 
				startActivity(addintent);
				finish();
			}
		}
	}
	protected void updateRecord(String recorddataid,String zmstr, String fmstr, String wystr ,String addtimestr,String isdo) {
		
		if(dataValid()){
			if(qydataisexist(addtimestr)){
				if(null != recorddataid ){
					String qyid = recordDataManager.findZuiHaoId(addtime);
					if(Integer.parseInt(recorddataid)==Integer.parseInt(qyid)){
						recordDataManager.updateRecordData(recorddataid,zmstr, fmstr, wystr ,isdo);
//						Intent intentset = new Intent(NewRecordAdd.this, TodayListNewActivity.class);
						Intent intentset = new Intent(NewRecordAdd.this, GridActivity.class);
						Bundle bundle = new Bundle(); 
						bundle.putString("Addtime", addtimestr);
						intentset.putExtras(bundle); 
						startActivity(intentset);
					}else{
						Toast.makeText(this, getString(R.string.save_already_exist), Toast.LENGTH_SHORT).show();
//						Intent intentset = new Intent(NewRecordAdd.this, TodayListNewActivity.class);
						Intent intentset = new Intent(NewRecordAdd.this, GridActivity.class);
						Bundle bundle = new Bundle(); 
						bundle.putString("Addtime", addtimestr);
						intentset.putExtras(bundle); 
						startActivity(intentset);
					}
				}
			}else{
				recordDataManager.updateRecordData(recorddataid,zmstr, fmstr, wystr,isdo);
//				Intent intentset = new Intent(NewRecordAdd.this, TodayListNewActivity.class);
				Intent intentset = new Intent(NewRecordAdd.this, GridActivity.class);
				Bundle bundle = new Bundle(); 
				bundle.putString("Addtime", addtimestr);
				intentset.putExtras(bundle); 
				startActivity(intentset);
			}
			
		}
	}

	private void seeddel(final String id,final String addtimestr){
		builder = new AlertDialog.Builder(NewRecordAdd.this)
		.setIcon(R.drawable.ic_launcher)
		.setTitle("温馨提示：")
		.setMessage("您是否要删除该数据吗")
		.setPositiveButton("确定",new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {
				if(null != id && !"".equals(id)){
					recordDataManager.openDataBase();
					boolean flag = recordDataManager.deleteRecordData(Integer.parseInt(id));
					if (!flag) {
						Toast.makeText(NewRecordAdd.this, getString(R.string.del_fail),Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(NewRecordAdd.this, getString(R.string.del_sucess),Toast.LENGTH_SHORT).show();
					}
				}else{
					Toast.makeText(NewRecordAdd.this, getString(R.string.del_fail),Toast.LENGTH_SHORT).show();
				}
//				Intent counterset = new Intent(NewRecordAdd.this,TodayListNewActivity.class);
				Intent counterset = new Intent(NewRecordAdd.this,GridActivity.class);
				Bundle bundle = new Bundle(); 
				bundle.putString("Addtime", addtimestr);
				counterset.putExtras(bundle); 
				startActivity(counterset);
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog,
					int whichButton) {
				builder.dismiss();
			}
		}).show();
		
	}
	
	public boolean dataValid() {
//		if (recordform_zm.getText().toString().trim().equals("")) {
//			Toast.makeText(this, getString(R.string.zm_empty), Toast.LENGTH_SHORT).show();
//			return false;
//		} else if (recordform_fm.getText().toString().trim().equals("")) {
//			Toast.makeText(this, getString(R.string.fm_empty), Toast.LENGTH_SHORT).show();
//			return false;
//		}else if (recordform_wy.getText().toString().trim().equals("")) {
//			Toast.makeText(this, getString(R.string.wy_empty), Toast.LENGTH_SHORT).show();
//			return false;
//		}
		if (recordform_zm.getText().toString().trim().equals("") && recordform_fm.getText().toString().trim().equals("") 
				&& recordform_wy.getText().toString().trim().equals("")) {
			Toast.makeText(this, getString(R.string.zm_fm_wy_empty), Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
	
	public boolean qydataisexist(String addtime){
		boolean isexist = false;
		if(null != isqy && !"".equals(isqy)){
			if(Integer.parseInt(isqy)==1){
				Integer flagisqy = recordDataManager.findZuiHaoCount(addtime);
				if(flagisqy>0){
					isexist = true;
				}else{
					isexist = false;
				}
			}else{
				isexist = false;
			}
		}
		return isexist;
	}
	
	@Override
	protected void onResume() {
		if (recordDataManager == null) {
			recordDataManager = new RecordDataManager(this);
			recordDataManager.openDataBase();
        }
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		 super.onDestroy();
		 if (recordDataManager  != null) {  
			 recordDataManager.closeDataBase(); 
			 recordDataManager = null;
		 } 
	}

	@Override
	protected void onPause() {
		if (recordDataManager != null) {
			recordDataManager.closeDataBase();
			recordDataManager = null;
        }
		super.onPause();
	}


}
